package com.shortLinked.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shortLinked.admin.common.biz.user.UserContext;
import com.shortLinked.admin.common.constant.RedisCacheConstant;
import com.shortLinked.admin.common.convention.exception.ClientException;
import com.shortLinked.admin.common.convention.exception.ServiceException;
import com.shortLinked.admin.common.convention.result.Result;
import com.shortLinked.admin.dao.entity.GroupDO;
import com.shortLinked.admin.dao.entity.GroupUniqueDO;
import com.shortLinked.admin.dao.mapper.GroupMapper;
import com.shortLinked.admin.dao.mapper.GroupUniqueMapper;
import com.shortLinked.admin.dto.req.ShortLinkGroupSortReqDTO;
import com.shortLinked.admin.dto.req.ShortLinkGroupUpdateReqDTO;
import com.shortLinked.admin.dto.resp.ShortLinkGroupRespDTO;
import com.shortLinked.admin.remote.ShortLinkActualRemoteService;
import com.shortLinked.admin.remote.dto.resp.ShortLinkGroupCountQueryRespDTO;
import com.shortLinked.admin.service.GroupService;
import com.shortLinked.admin.utils.RandomUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

import static com.shortLinked.admin.common.biz.user.ColoredOutput.RED;
import static com.shortLinked.admin.common.biz.user.ColoredOutput.RESET;

/**
 * 短链接接口实现层
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class GroupServiceImpl extends ServiceImpl<GroupMapper, GroupDO> implements GroupService {
    private final RBloomFilter<String> gidRegisterCachePenetrationBloomFilter;

    private final GroupUniqueMapper groupUniqueMapper;

    private final ShortLinkActualRemoteService shortLinkActualRemoteService;

    private final RedissonClient redissonClient;

    @Value("${short-link.group.max-num}")
    private Integer groupMaxNum;

    @Override
    public void saveGroup(String groupName) {
        System.out.println(RED+"这里是:saveGroup"+RESET);
        this.saveGroup(UserContext.getUsername(), groupName);
    }

    @Override
    public void saveGroup(String username, String groupName) {
        System.out.println(RED+"这里是:saveGroup2"+RESET);
        // 限制用户创建分组数量 - 通过分布式锁来实现
        RLock lock = redissonClient.getLock(String.format(RedisCacheConstant.LOCK_GROUP_CREATE_KEY, username));
        // "short-link:lock_group-create:%s", username
        lock.lock();
        try {
            LambdaQueryWrapper<GroupDO> lambdaQueryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                    .eq(GroupDO::getUsername, username)
                    .eq(GroupDO::getDelFlag, 0);
            //封装操作
            List<GroupDO> groupDOList = baseMapper.selectList(lambdaQueryWrapper);
            //groupDOList当前用户的所有分组,对应信息
            //数据库中查找是否有该用户的分组信息
            if (CollUtil.isNotEmpty(groupDOList) && groupDOList.size() == groupMaxNum) {
                throw new ClientException(String.format("已超过该用户创建的最大分组数量：%d", groupMaxNum));
            }
            int retryCount = 0;
            int maxRetries = 10;
            String gid = null;
            while (retryCount < maxRetries) {
                //重试机制的循环，最多重试 10 次。每次重试的目的是生成一个唯一的分组 ID。
                gid = saveGroupUniqueReturnGid();
                if (StrUtil.isNotBlank(gid)) {
                    GroupDO groupDO = GroupDO.builder()
                            //链式调用
                            .sortOrder(0)
                            .gid(gid)
                            .username(username)// 创建该分组的用户名
                            .name(groupName)//分组名
                            .build();
                    baseMapper.insert(groupDO);
                    //插入数据库
                    gidRegisterCachePenetrationBloomFilter.add(gid);
                    //插入布隆过滤器
                    break;
                }
                retryCount++;
            }
            if (StrUtil.isEmpty(gid)) {
                throw new ServiceException("生成分组标识频繁");
            }
        } finally {
            lock.unlock();
        }
    }

    /**
     * 生成 gid，并判断布隆过滤器中是否有了 gid, gid 要唯一
     */
    private String saveGroupUniqueReturnGid() {
        System.out.println(RED+"这里是:saveGroupUniqueReturnGid"+RESET);
        String gid = RandomUtil.generateRandomString();
        //随机生成六位gid
        if (!gidRegisterCachePenetrationBloomFilter.contains(gid)) {
            GroupUniqueDO groupUniqueDO = GroupUniqueDO.builder()
                    .gid(gid)
                    .build();
            try {
                groupUniqueMapper.insert(groupUniqueDO);
            } catch (DuplicateKeyException ex) {
                return null;
            }
        }
        return gid;
    }

    /**
     * @param gid 短链接分组标识GID
     * @return 是否存在 true 标识不存在  false 标识存在
     */
    private boolean hasGID(String username, String gid) {
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getGid, gid)
                .eq(GroupDO::getUsername, Optional.ofNullable(username).orElse(UserContext.getUsername()));
        GroupDO hasGroupFlag = baseMapper.selectOne(queryWrapper);
        return hasGroupFlag == null;
    }

    @Override
    public List<ShortLinkGroupRespDTO> listGroup() {
        //搜索每个组的短链接数量
        System.out.println(RED+"这里是:listGroup");
        LambdaQueryWrapper<GroupDO> queryWrapper = Wrappers.lambdaQuery(GroupDO.class)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getDelFlag, 0)
                .orderByDesc(GroupDO::getSortOrder, GroupDO::getUpdateTime);
        //降序
        List<GroupDO> groupDOList = baseMapper.selectList(queryWrapper);
//        查询用户的所有分组信息
        Result<List<ShortLinkGroupCountQueryRespDTO>> listResult = shortLinkActualRemoteService
                .listShortLinkGroupQueryCount(groupDOList.stream().map(GroupDO::getGid).toList());
        //listResult为每一组短链接的数量
        // 获取到分组对象（gid，shortLinkGroupCount）
        List<ShortLinkGroupRespDTO> shortLinkGroupRespDTOList = BeanUtil.copyToList(groupDOList, ShortLinkGroupRespDTO.class);// 查询出来的是 GroupDO对象  进行转化
        // 再对上面的对象，shortLinkGroupCount 属性进行一个填充
        shortLinkGroupRespDTOList.forEach(each -> {
            Optional<ShortLinkGroupCountQueryRespDTO> first = listResult.getData().stream().filter(item ->
                    Objects.equals(item.getGid(), each.getGid())).findFirst();
            first.ifPresent(item -> each.setShortLinkGroupCount(first.get().getShortLinkGroupCount()));
        });
        //如果在 listResult.getData() 中找到了与当前分组 (each) 对应的 ShortLinkGroupCountQueryRespDTO 对象（通过 gid 匹配），
        // 则将 shortLinkGroupCount 的值设置到 each 对象中
        return shortLinkGroupRespDTOList;
    }

    @Override
    public void updateGroup(ShortLinkGroupUpdateReqDTO requestParam) {
        System.out.println(RED+"这里是:updateGroup");
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, requestParam.getGid());
        GroupDO buildDO = GroupDO.builder()
                .name(requestParam.getName())
                .build();
        baseMapper.update(buildDO, updateWrapper);  // 要修改的实体类
    }

    @Override
    public void deleteGroup(String gid) {
        System.out.println(RED+"这里是:deleteGroup");
        LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                .eq(GroupDO::getDelFlag, 0)
                .eq(GroupDO::getUsername, UserContext.getUsername())
                .eq(GroupDO::getGid, gid);
        GroupDO buildDO = new GroupDO();  // 不能使用建造者模式，属性不显示
        buildDO.setDelFlag(1);
        baseMapper.update(buildDO, updateWrapper);  // 要修改的实体类
    }

    @Override
    public void sortGroup(List<ShortLinkGroupSortReqDTO> requestParam) {
        System.out.println(RED+"这里是:sortGroup");
        requestParam.forEach(each -> {
            LambdaUpdateWrapper<GroupDO> updateWrapper = Wrappers.lambdaUpdate(GroupDO.class)
                    .eq(GroupDO::getGid, each.getGid())
                    .eq(GroupDO::getDelFlag, 0)
                    .eq(GroupDO::getUsername, UserContext.getUsername());
//            获取用户名,gid,delflag用于查询组
            GroupDO build = GroupDO.builder()
                    .sortOrder(each.getSortOrder())
                    .build();
            baseMapper.update(build, updateWrapper);
        });
    }
}
